<?php
/**
 * Description of FormBuscaViewGenerator
 *
 * @author Magno
 */
class FormBuscaViewGenerator extends ViewGenerator{

    private $attBuscaForm;

    public function __construct($tableMeta, $viewParams) {
        $this->attBuscaForm = "";
        parent::__construct($tableMeta, $viewParams, Constantes::$TEMPLATES_VIEW_DIR."formBusca.bloum");
    }

    public function generate() {
        parent::generateNames();        
        $this->generateAttValues();
        return $this->templateView;
    }

    public function generateAttValues(){
        $this->generateAttValuesParam($this->tableMeta);
    }

    public function generateAttValuesParam($table){

        $tableName = $table->getName();
        $attributes = $table->getAttributes();
        $attrsKeys = array_keys($attributes);
        
        for ($i = 0; $i < count($attrsKeys); $i++) {
            $att = $attributes[$attrsKeys[$i]];
            $name = $att->getName();

            if(!$att->isImportant() || ($att->isPrimaryKey() && !$att->isForeignKey()))  continue;

            if(!$att->isForeignKey()){
                $this->attBuscaForm .= '<div class="float-left gutter-right">{form_input name="'.$name.'" label="'.ucfirst($name).'"}</div>';
                $this->attBuscaForm .= "\n\t";
            }
            else{
                $tbFkName = str_replace("ID", "", $name);
                $fks = $table->getFKReferences();
                $fkMeta = null;
                foreach ($fks as $fk) {
                    foreach ($fk->getAttributes() as $fkAtt) {
                        if(strcmp(strtolower($fkAtt->getName()), strtolower($tbFkName."ID")) == 0){
                            $fkMeta = $fk;
                            break;
                        }
                    }
                    if($fkMeta != null) break;
                }
                if($fkMeta == null)
                    throw new Exception ("Tabela (".$tbFkName.") Referenciada Na Herança com (".$this->tableMeta->getName().") Não Encontrada!!!");

                if($fkMeta->isExtends())
                    $this->generateAttValuesParam ($fkMeta->getTableReference());

                $tbReference = $fkMeta->getTableReference()->getName();
                $tab = "\n\t\t\t\t";
                if(strcmp($fkMeta->getTypeForm(), Constantes::$TYPE_FORM_COMBO) == 0){
                    $this->attBuscaForm .= '<div class="float-left gutter-right">'.$tab."\t".'<label for="'.$tbReference.'ID">'.ucfirst($tbReference).'</label>{html_options name='.$tbReference.'ID id='.$tbReference.'ID options=$'.$tbReference.'s}'.$tab.'</div>';
                }
            }

        }

        $this->templateView = str_replace(Constantes::$TPL_VIEW_FORM_ATT_BUSCA_FORM, $this->attBuscaForm, $this->templateView);

    }

    public function generateFile($generate = true){
        if($generate)
            $this->generate();
        parent::generateFile("formBusca");
    }
}
?>
